package com.lzh.dlykserver.controller;

import com.github.pagehelper.PageInfo;
import com.lzh.dlykserver.entity.TProduct;
import com.lzh.dlykserver.query.ProductDTO;
import com.lzh.dlykserver.query.ProductQuery;
import com.lzh.dlykserver.result.R;
import com.lzh.dlykserver.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class ProductController {

    private final ProductService productService;

    /**
     * 获取产品列表
     * @param current
     * @param productQuery
     * @return
     */
    @GetMapping("/products")
    public R getProducts(@RequestParam(value = "current", required = false) Integer current,
                         ProductQuery productQuery) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TProduct> pageInfo = productService.getProducts(current, productQuery);
        return R.OK(pageInfo);
    }

    /**
     * 添加产品
     * @param productDTO
     * @param token
     * @return
     */
    @PostMapping("/product/add")
    public R addProduct(@RequestBody ProductDTO productDTO,
                        @RequestHeader("Authorization") String token) {
        productDTO.setToken(token);
        int i = productService.addProduct(productDTO);
        return i > 0 ? R.OK() : R.FAIL();
    }

    /**
     * 编辑产品
     * @param productDTO
     * @param token
     * @return
     */
    @PutMapping("/product/edit")
    public R editProduct(@RequestBody ProductDTO productDTO,
                         @RequestHeader("Authorization") String token) {
        productDTO.setToken(token);
        int i = productService.editProduct(productDTO);
        return i > 0 ? R.OK() : R.FAIL();
    }

    /**
     * 获取产品详情
     * @param id
     * @return
     */
    @GetMapping("/product/{id}")
    public R getProductById(@PathVariable("id") Integer id) {
        TProduct product = productService.getProductById(id);
        return R.OK(product);
    }

    /**
     * 删除产品
     * @param id
     * @return
     */
    @DeleteMapping("/product/{id}")
    public R deleteProduct(@PathVariable("id") Integer id) {
        int i = productService.deleteProduct(id);
        return i > 0 ? R.OK() : R.FAIL();
    }

    /**
     * 批量删除产品
     * @param ids
     * @return
     */
    @DeleteMapping("/product")
    public R batchDeleteProduct(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int i = productService.batchDeleteProduct(idList);
        return i > 0 ? R.OK() : R.FAIL();
    }
}
